package com.library.service.impl;

import com.alibaba.fastjson.JSON;
import com.library.common.core.domain.AjaxResult;
import com.library.common.exception.base.BaseException;
import com.library.common.utils.SecurityUtils;
import com.library.domain.BoMembers;
import com.library.mapper.BoMembersMapper;
import com.library.service.IAppLoginService;
import com.library.vo.LoginModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author julyWhj
 * @Description $
 * @Date 2022/3/24 5:29 下午
 **/
@Service
public class AppLoginServiceImpl implements IAppLoginService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private BoMembersMapper boMembersMapper;


    private static final String LOGIN_KEY = "app_login_key:";

    @Override
    public AjaxResult login(LoginModel loginModel) {
        BoMembers boMembers = boMembersMapper.checkPhoneUnique(loginModel.getPhone());
        if (Objects.isNull(boMembers)) {
            throw new BaseException("appLogin", "301", null, "手机号不能为空");
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(LOGIN_KEY.concat(token), JSON.toJSONString(boMembers), 30, TimeUnit.DAYS);
        return AjaxResult.success("登录成功", token);
    }

    @Override
    public AjaxResult userInfo() {
        Long userId = SecurityUtils.getUserId();
        BoMembers boMembers = boMembersMapper.selectBoMembersById(userId);
        return AjaxResult.success("用户信息获取成功", boMembers);
    }
}
